package com.temp.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.temp.dto.SearchDonationDTO;
import com.temp.entity.Donation;
import com.temp.vo.DonationDateVO;
import com.temp.vo.DonationUserVO;
import com.temp.vo.DonationVO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.math.BigDecimal;
import java.util.List;

@Mapper
public interface DonationMapper extends BaseMapper<Donation> {

    List<DonationUserVO> findAllByCampaign(SearchDonationDTO donationDTO);

    List<Donation> findAllUserDonations(SearchDonationDTO donationDTO);

    Integer countAllUserDonations(SearchDonationDTO donationDTO);

    Integer countAllByCampaign(SearchDonationDTO donationDTO);

    BigDecimal countDonationByRobot(Long campaignId);

    @Select("SELECT " +
            "    COUNT(DISTINCT d.campaign_id) as campaigns, " +
            "    SUM(d.amount) as amount, " +
            "    ROUND((" +
            "        SELECT COUNT(*) " +
            "        FROM (" +
            "            SELECT user_id, SUM(amount) as user_total " +
            "            FROM donation " +
            "            GROUP BY user_id" +
            "            HAVING user_total <= (SELECT SUM(amount) FROM donation WHERE user_id = #{userId})" +
            "        ) as t" +
            "    ) * 100.0 / (" +
            "        SELECT COUNT(DISTINCT user_id) FROM donation" +
            "    ), 2) as amount_percentile " +
            "FROM donation d " +
            "WHERE d.user_id = #{userId}")
    DonationVO countOneSelfDonations(@Param("userId") Long userId);

    @Select("SELECT " +
            "    DATE(created_at) as donation_date, " +
            "    COALESCE(SUM(amount), 0) as total_amount, " +
            "    COUNT(*) as donation_count " +
            "FROM donation " +
            "WHERE campaign_id = #{campaignId} " +
            "AND created_at IS NOT NULL " +
            "GROUP BY DATE(created_at) " +
            "ORDER BY donation_date ASC")
    List<DonationDateVO> countDonationDate(@Param("campaignId") Long campaignId);
}
